//
//  YXComUtil.m
//  SeniorCarRepairing
//
//  Created by xmdfst on 16/9/29.
//  Copyright © 2016年 xmdfst. All rights reserved.
//

#import "YXComUtil.h"
#import <sys/sysctl.h>
#import <CommonCrypto/CommonDigest.h>
#import "CoreTextUtil.h"
#import "RootViewController.h"

@implementation YXComUtil
#pragma mark 图片按大小生成
+(UIImage*)originImage:(UIImage *)image scaleToSize:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片http://7tt037.com2.z0.glb.qiniucdn.com/142051878284275237.jpg
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

#pragma mark 获取路径
+(NSString*)getTempFilePath
{
    return NSTemporaryDirectory();
}
+(NSString*)getDocumentPath
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}

+(NSString*)getLibraryPath
{
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    return path;
}

+(NSString*)getCachePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return paths[0];
}


+(BOOL)isEqualString:(NSString*)str1 toString:(NSString*)str2
{
    if (str1.length == 0 && str2.length == 0) {
        return YES;
    }
    
    return [str1 isEqualToString:str2];
}

+(NSString*)getSafeString:(NSString*)string;
{
    if ([string isKindOfClass:[NSString class]] == NO) {
        return @"";
    }
    return string;
}

+(void)alertWithTitle:(NSString*)title content:(NSString*)content
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action];
    [[RootViewController instance] presentViewController:alert animated:YES completion:nil];
}

+(void)alert:(NSString*)content
{
    [YXComUtil alertWithTitle:nil content:content];
}

+(NSString*)toPinyin:(NSString*)src
{
    if (src == nil || [src isKindOfClass:[NSString class]] == NO) {
        return nil;
    }
    NSMutableString *source = [[NSMutableString alloc] initWithString:src];
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
    return [[NSString alloc] initWithString:source.lowercaseString];
}


+(UIImage*)fixOrientation:(UIImage*)srcImg orientation:(UIImageOrientation)ori
{
    if (ori == UIImageOrientationUp) return srcImg;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (ori) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (ori) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height,
                                             CGImageGetBitsPerComponent(srcImg.CGImage), 0,
                                             CGImageGetColorSpace(srcImg.CGImage),
                                             CGImageGetBitmapInfo(srcImg.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (srcImg.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.height,srcImg.size.width), srcImg.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,srcImg.size.width,srcImg.size.height), srcImg.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


+(UIImage *)fixOrientation:(UIImage *)srcImg
{
    return [YXComUtil fixOrientation:srcImg orientation:srcImg.imageOrientation];
}


// 判断小数，是否有小数部分
+(BOOL)isFloatHasDecimal:(double)num
{
    long long integer = num;
    if (num - integer > 0 ) {
        return YES;
    }else{
        return NO;
    }
}


+(BOOL)isToday:(long long)timeMinSec
{
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeMinSec/1000];
    NSDate *today = [NSDate date];
    
    return [YXComUtil isSameDay:date date2:today];
}

+(BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2
{
    NSDateComponents *comp_1 = [[NSCalendar currentCalendar] components:NSCalendarUnitEra |NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date1];
    NSDateComponents *comp_2 = [[NSCalendar currentCalendar] components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date2];
    if([comp_1 day] == [comp_2 day] &&
       [comp_1 month] == [comp_2 month] &&
       [comp_1 year] == [comp_2 year] &&
       [comp_1 era] == [comp_2 era]) {
        return YES;
    }else{
        return NO;
    }
}


+(NSDate*)date:(NSDate*)date withOffsetDay:(NSInteger)offsetDay
{
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:offsetDay];
    NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *ret = [calender dateByAddingComponents:comps toDate:date options:0];
    comps = nil;
    calender = nil;
    return ret;
}

/* 周一开始 1 2 3 。。。。*/

+(NSInteger)getWeakDayOfDate:(NSDate*)date
{
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday fromDate:date];
    NSInteger ret = dateComponents.weekday;
    if (ret == 1) {
        ret = 7;
    }else{
        ret--;
    }
    return ret;
}
+(NSString *)dateFromLongLong:(long long)msSince1970 dateFormat:(NSString *)format
{
    if (msSince1970 == 0) {
        return @"";
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:msSince1970 / 1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = format;
    NSString *strDate = [formatter stringFromDate:date];
    return strDate;
}
+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    return platform;
}

/**
 *  @author LYX, 16-09-29 17:09:44
 *
 *  获取相机权限
 *
 *  @return 权限状态
 *
 *  @since <#1.0#>
 */
+(AVAuthorizationStatus)cameraAuthorStatus
{
    NSString *mediaType = AVMediaTypeVideo;// Or AVMediaTypeAudio
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    return authStatus;
}


+ (NSString *)getCurrentBundleVersion{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    return infoDict[@"CFBundleVersion"];
}
+ (NSString *)getCurrentBundleShortVersionString{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    return infoDict[@"CFBundleShortVersionString"];
}
+ (NSString *)getCurrentSystemVersion{
    return [[UIDevice currentDevice] systemVersion];
}
// 获取boundleId
+(NSString*)getBundleId{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    return infoDict[@"CFBundleIdentifier"];
}

/**
 * 生成UUID
 */
+(NSString*)createUUID
{
    CFUUIDRef uuidObj = CFUUIDCreate(nil);
    
    NSString *uuidString = (__bridge_transfer NSString*)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString;
}


/**
 *  @author LYX, 16-10-14 11:10:23
 *
 *  将字符串进行MD5加密
 *
 *  @param inputStr 要加密的字符串
 *
 *  @return 加密后的字符串
 */
+(NSString *)encryptStringWithMD5:(NSString *)inputStr
{
    const char *newStr = [inputStr UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(newStr,(unsigned int)strlen(newStr),result);
    NSMutableString *outStr = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for(int i = 0;i<CC_MD5_DIGEST_LENGTH;i++){
        [outStr appendFormat:@"%02X",result[i]];//注意：这边如果是x则输出32位小写加密字符串，如果是X则输出32位大写字符串
    }
    return outStr;
}


/**
 将时间戳转成字符串格式
 
 @param time 时间戳
 @param formate 格式：如@“yyyyMMddHHmmss”
 @return 字符串的时间
 */
+(NSString *)changeTimeToTimeStr:(long long)time formate:(NSString*)formate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = formate;
    return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:time]];
    
}


+ (NSData *)compressImage:(UIImage *)image
{
    NSData *data=UIImageJPEGRepresentation(image, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
            data=UIImageJPEGRepresentation(image, 0.1);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(image, 0.5);
        }else if (data.length>200*1024) {//0.25M-0.5M
            data=UIImageJPEGRepresentation(image, 0.9);
        }
    }
    return data;
}

#pragma mark - 获取样式价格
+(NSMutableAttributedString *)getAttributedStrOfPrice:(double)price
{
    return [YXComUtil getAttributedStrOfPrice:price centerFontSize:16];
}

+(NSMutableAttributedString *)getAttributedStrOfPrice:(double)price centerFontSize:(NSInteger)font
{
    NSString *priceStr = [NSString stringWithFormat:@"%.2lf",price];
    NSArray *arr = [priceStr componentsSeparatedByString:@"."];
    if (arr.count > 1) {
        NSMutableAttributedString *str1 = [[NSMutableAttributedString alloc]initWithString:@"¥"];
        NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc]initWithString:[arr firstObject]];
        NSMutableAttributedString *str3 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@".%@",[arr lastObject]]];
        
        [CoreTextUtil setAttributeString:str1 font:FONT(font-6) range:NSMakeRange(0, str1.length)];
        [CoreTextUtil setAttributeString:str2 font:FONT(font) range:NSMakeRange(0, str2.length)];
        [CoreTextUtil setAttributeString:str3 font:FONT(font-7) range:NSMakeRange(0, str3.length)];
        
        [str1 appendAttributedString:str2];
        [str1 appendAttributedString:str3];
        return str1;
    }
    
    return nil;
}

#pragma mark- 获取时间
+(NSString*)getTimeStr:(NSString*)time
{
    NSDateFormatter *formate = [[NSDateFormatter alloc]init];
    [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    return [formate stringFromDate:[NSDate dateWithTimeIntervalSince1970:time.longLongValue]];
}

#pragma mark - alert
/**
 弹窗

 @param title 标题
 @param actionName 点击确定的方法名
 @param controller 控制器
 @param preferredStyle 弹窗显示格式
 */
+(void)createAlertWithTitle:(NSString*)title sureActionName:(NSString*)actionName viewController:(UIViewController*)controller preferredStyle:(UIAlertControllerStyle)preferredStyle
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:preferredStyle];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action2];

    
    if (actionName.length > 0) {
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            if ([controller respondsToSelector:NSSelectorFromString(actionName)]) {
                SEL selector = NSSelectorFromString(actionName);
                ((void(*)(id,SEL))[controller methodForSelector:selector])(controller, selector);
            }
        }];
        [alert addAction:action1];
    }
   
    
    
    [controller presentViewController:alert animated:YES completion:nil];
}

+(void)createAlertWithTitle:(NSString*)title viewController:(UIViewController*)controller
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action2];
    [controller presentViewController:alert animated:YES completion:nil];
}

#pragma mark - image scale utility

/**
 将图片按屏幕大小的比例同等放大或者缩小成屏幕大小
 
 @param sourceImage 原图
 @return 改变后的图片
 */
+(UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage
{
    if (sourceImage.size.width < SCREEN_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = SCREEN_WIDTH;
        btWidth = sourceImage.size.width * (SCREEN_WIDTH / sourceImage.size.height);
    } else {
        btWidth = SCREEN_WIDTH;
        btHeight = sourceImage.size.height * (SCREEN_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [YXComUtil imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

+(UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

@end
